<?php
require_once dirname(dirname(__FILE__)).'/abstract.php';

class SF_PromoteEvents_AutoUpdateSpecialPrice extends Mage_Shell_Abstract
{
    public function autoUpdate()
	{
		$eventCode = $this->getArg("code");
		$action = $this->getArg("action"); /*如果action为cancel,则还原为原价*/
		
		// $eventCode = '3c_products_collection';
		if(!$eventCode) 
		{
			Mage::log('更新特价失败，Event Code为空！DEBUG_ERROR');
			exit;
		}
		$eventsData	= Mage::getModel('promoteevents/events')->getCollection()
					  ->addFieldToFilter('event_code',$eventCode)
					  ->getFirstItem();
		if(!$eventsData->getData())
		{
			Mage::log('更新特价失败：DEBUG_ERROR');
			Mage::log('Event Code不存在：'. $eventCode);
			exit;
		}
		
		$fromDate 	= $eventsData['from_date'];
		$toDate   	= $eventsData['to_date'];
		$eventsId 	= $eventsData['id'];
		$eventsProductCollection = Mage::getModel('promoteevents/product')->getCollection()
								    ->addFieldToFilter('p_id', $eventsId)
									->addFieldToFilter('status', 1)
									->addFieldToFilter('is_sub_product', 0);
		if(! $eventsProductData = $eventsProductCollection->getData()) exit;
		
		$log = array();
		foreach($eventsProductData as $data)
		{
			$productSku = $data['product_sku'];
			$specialPrice = $data['special_price'];
			if($specialPrice <= 0) continue;
			
			$_product = Mage::getModel('catalog/product')->loadByAttribute('sku',$productSku);
    		if(!$_product) continue;
			/* action == cancel,则设置special price为空 */
			if($action == 'cancel'){
				$this->updateSpecialPrice($_product);
				$log[$_product->getId()] = array($productSku,$_product->getTypeId());
				
			}else{
				if($_product->getTypeId() == 'simple')
				{
					$this->updateSpecialPrice($_product,$specialPrice,$fromDate,$toDate);
					$log[$_product->getId()] = array($productSku,$_product->getTypeId(),$specialPrice,$fromDate,$toDate);
				}
				if($_product->getTypeId() == 'configurable')
				{
					$this->updateSpecialPrice($_product,$specialPrice,$fromDate,$toDate);
					$log[$_product->getId()] = array($productSku,$_product->getTypeId(),$specialPrice,$fromDate,$toDate);
				}
			}
			
			
			
		}
		
		Mage::log('更新特价日志：');
		Mage::log('共更新：'.count($log).'条记录');
		Mage::log($log);
	}

    public function updateSpecialPrice($product, $price=null, $fromDate=null, $toDate=null)
    {
		
    	Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
    	$product->setSpecialPrice($price)
			   ->setSpecialFromDate($fromDate)
			   ->setSpecialFromDateIsFormated(true)
			   ->setSpecialToDate($toDate)
			   ->setSpecialToDateIsFormated(true)
			   // ->setUrlKey(false)
               ->save();
    }
	

    public function run()
	{
		$this->autoUpdate();
	}
}


$C = new SF_PromoteEvents_AutoUpdateSpecialPrice();
$C->run();
     